package com.funmi.lizip.security.entity;

import com.funmi.lizip.entity.AdminUser;
import com.funmi.lizip.entity.Role;
import com.funmi.lizip.entity.User;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;


import java.security.Permission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class SecurityAdminUser extends org.springframework.security.core.userdetails.User {
    //当前登录用户
    @Getter
    private AdminUser currentUser;

    public SecurityAdminUser(AdminUser currentUser, List<Role> roleList, List<Permission> permissionList) {
        this(currentUser.getUsername(), currentUser.getPassword(), true, true, true, true, parsePermission(roleList, permissionList));
        this.currentUser = currentUser;
    }

    public SecurityAdminUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }


    private static Collection<? extends GrantedAuthority> parsePermission(List<Role> roleList, List<Permission> permissionList) {
        Collection<GrantedAuthority> authorities = new ArrayList<>();

        /*for(Role role : roleList) {
            if(StringUtils.isEmpty(role.getRoleCode())) {
                continue;
            }
            // 生成授权对象
            // 角色必须有前缀"ROLE_"
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role.getRoleCode());
            authorities.add(authority);
        }

        for(Permission permission : permissionList) {
            if(StringUtils.isEmpty(permission.getPermissionValue())) {
                continue;
            }
            // 生成授权对象
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getPermissionValue());
            authorities.add(authority);
        }*/

        return authorities;
    }
}